package com.onlyxiahui.common.action.description.handler.impl.title;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.onlyxiahui.common.action.description.DocumentContext;
import com.onlyxiahui.common.action.description.annotation.DocModule;
import com.onlyxiahui.common.action.description.annotation.DocTitle;
import com.onlyxiahui.common.action.description.common.TagConstant;
import com.onlyxiahui.common.action.description.handler.ModuleTitleHandler;
import com.onlyxiahui.common.action.description.util.JavaTagUtil;
import com.thoughtworks.qdox.model.JavaClass;

/**
 * Description <br>
 * Date 2020-01-08 08:46:54<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class ModuleCommentTitleHandler implements ModuleTitleHandler {

	/**
	 * 
	 */
	Pattern p = Pattern.compile("(?i)title(.*)<br>");

	@Override
	public boolean support(DocumentContext context, Class<?> classType, String text) {

		boolean hasModuleDefine = null != classType.getAnnotation(DocModule.class);
		boolean hasTitle = null != classType.getAnnotation(DocTitle.class);

		String className = classType.getName();
		JavaClass jc = context.getSourceBox().getJavaClassByName(className);
		boolean hasTag = false;
		if (null != jc) {
			hasTag = null != jc.getTagByName(TagConstant.DOC_TITLE);
		}
		boolean isFind = false;
		if (null != text) {
			Matcher m = p.matcher(text);
			isFind = m.find();
		}
		return (!hasModuleDefine && !hasTitle) && (isFind || hasTag);
	}

	@Override
	public String handle(DocumentContext context, Class<?> classType, String text) {
		String title = null;
		if (null != text) {
			Matcher m = p.matcher(text);
			if (m.find()) {
				// m.group(1)不包括这两个字符
				title = (m.group(1));
			}
		}
		String className = classType.getName();
		JavaClass jc = context.getSourceBox().getJavaClassByName(className);
		if (null != jc) {
			String value = JavaTagUtil.getTagValueByName(jc, TagConstant.DOC_TITLE);
			if (null != value && !value.isEmpty()) {
				title = value;
			}
		}
		return title;
	}
}
